package com.fanhang.samples.jfinal.utils;

/**
 * SQL拼接工具类
 * 
 * @author 樊航
 */
public class SqlBuilder implements CharSequence {

	private StringBuilder sql;

	public SqlBuilder() {
		this(64);
	}

	public SqlBuilder(int capacity) {
		sql = new StringBuilder(capacity);
	}

	public SqlBuilder append(Object obj) {
		sql.append(obj);
		return this;
	}

	public SqlBuilder append(CharSequence cs) {
		sql.append(cs);
		return this;
	}

	public SqlBuilder append(boolean o) {
		sql.append(o);
		return this;
	}

	public SqlBuilder append(char o) {
		sql.append(o);
		return this;
	}

	public SqlBuilder append(Number number) {
		sql.append(number);
		return this;
	}
	
	private SqlBuilder wrap(Object obj, CharSequence beforeItem, CharSequence afterItem) {
		if (obj == null) {
			return this;
		}
		return this.append(beforeItem).append(obj).append(afterItem);
	}
	
	public SqlBuilder wrap(Object obj, CharSequence wrap) {
		if (obj == null) {
			return this;
		}
		return this.append(wrap).append(obj).append(wrap);
	}
	
	public SqlBuilder wrap(Object obj) {
		if (obj == null) {
			return this;
		}
		return this.append("'").append(obj).append("'");
	}
	
	private SqlBuilder forEachWrap(Object[] array, String separator, CharSequence beforeItem, CharSequence afterItem) {
		if (array == null || array.length == 0) {
			return this;
		}
		this.wrap(array[0], beforeItem, afterItem);
		for (int i = 1; i < array.length; i++) {
			this.append(separator).wrap(array[i], beforeItem, afterItem);
		}
		return this;
	}
	
	public SqlBuilder forEachWrap(Object[] array, String separator, CharSequence wrap) {
		return forEachWrap(array, separator, wrap, wrap);
	}
	
	public SqlBuilder forEach(Object[] array, String separator) {
		return forEachWrap(array, separator, "");
	}
	
	public SqlBuilder where(String key, Object value) {
		return this.append(" and ").append(key).append("=").wrap(value);
	}
	
	public SqlBuilder where(String key, Number value) {
		return this.append(" and ").append(key).append("=").append(value);
	}
	
	public SqlBuilder delete(int start, int end) {
		sql.delete(start, end);
		return this;
	}

	public SqlBuilder clean() {
		return delete(0, sql.length());
	}

	public SqlBuilder deleteCharAt(int index) {
		sql.deleteCharAt(index);
		return this;
	}

	public String getSql() {
		return sql.toString();
	}

	public void setSql(String sql) {
		this.clean().append(sql);
	}

	@Override
	public int length() {
		return sql.length();
	}

	@Override
	public char charAt(int index) {
		return sql.charAt(index);
	}

	@Override
	public CharSequence subSequence(int start, int end) {
		return sql.subSequence(start, end);
	}

	@Override
	public String toString() {
		return sql.toString();
	}
}
